package com.hsjk.szwj.module.pay.mq;

import cn.hutool.json.JSONUtil;
import com.hsjk.szwj.framework.mq.core.RedisMQTemplate;
import com.hsjk.szwj.module.pay.dal.dataobject.config.PayOrderDivisionMQ;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author chenjiawei
 * @desc 更新订单自动分账业务延迟队列
 * @Date 2023/08/23 09:32
 **/
@Component
@Slf4j
public class UpdatePayOrderAutoDivisionDelayQueue {
    private RedissonClient redissonClient;
    private RDelayedQueue<PayOrderDivisionMQ> delayQueue;
    private RBlockingQueue<PayOrderDivisionMQ> blockingQueue;

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private String port;

    @Value("${spring.redis.password}")
    private String password;

    @Resource
    private RedisMQTemplate redisMQTemplate;


    @PostConstruct
    public void init() {
        initDelayQueue();
        startDelayQueueConsumer();
    }

    private void initDelayQueue() {
        Config config = new Config();
        SingleServerConfig serverConfig = config.useSingleServer();
        serverConfig.setAddress("redis://" + host + ":" + port + "");
        serverConfig.setPassword(password);
        redissonClient = Redisson.create(config);
        String blockQueueName = "UPDATE-PAY-ORDER-AUTO-DIVISION";
        blockingQueue = redissonClient.getBlockingQueue(blockQueueName);
        delayQueue = redissonClient.getDelayedQueue(blockingQueue);
    }

    private void startDelayQueueConsumer() {
        String consumerName = "UPDATE-PAY-ORDER-AUTO-DIVISION-CONSUMER";
        new Thread(() -> {
            while (true) {
                try {
                    PayOrderDivisionMQ payOrderDivision = blockingQueue.take();
                    log.info("接收到延迟任务:{}", JSONUtil.toJsonStr(payOrderDivision));
                    redisMQTemplate.send(payOrderDivision);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, consumerName).start();
    }

    public void offerTask(PayOrderDivisionMQ payOrderDivision, long seconds) {
        log.info("添加延迟任务:{} 延迟时间:{}s", JSONUtil.toJsonStr(payOrderDivision), seconds);
        delayQueue.offer(payOrderDivision, seconds, TimeUnit.SECONDS);

    }

}
